﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;

namespace UserInterfaceLayer.User
{
    public partial class Reserve : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewState["SelectedRoom"] = new List<Room_ViewStateItem>();
                ViewState["SearchRoom"] = new List<Room_ViewStateItem>();
                ViewState["SearchPerson"] = new List<Person_ViewStateItem>();
                ViewState["SelectedPerson"] = new List<Person_ViewStateItem>();
            }

            lblNoHeadmanSelected.Visible = false;
            lblNoPersonSelected.Visible = false;
            lblNoRoomSelected.Visible = false;
            lblSuccessful.Visible = false;
            lblFailure.Visible = false;
            lblInvalidInput.Visible = false;

            if (!IsPostBack)
            {
                FillFromDropDown();
                FillToDropDown();
                FillRefererDropDown();
            }
        }

        void Page_PreRender(object sender, EventArgs e)
        {
            DataAccessLayer.linqDatabaseDataContext db = new DataAccessLayer.linqDatabaseDataContext();

            lstRoom.DataSource = Room_ListViewItem_Pro.Convert(db, (List<Room_ViewStateItem>)ViewState["SearchRoom"]);
            lstRoom.DataBind();

            lstSelectedRoom.DataSource = Room_ListViewItem_Pro.Convert(db, (List<Room_ViewStateItem>)ViewState["SelectedRoom"]);
            lstSelectedRoom.DataBind();

            lstPerson.DataSource = Person_ViewStateItem_Pro.Convert(db, (List<Person_ViewStateItem>)ViewState["SearchPerson"]);
            lstPerson.DataBind();

            lstSelectedPerson.DataSource = Person_ViewStateItem_Pro.Convert(db, (List<Person_ViewStateItem>)ViewState["SelectedPerson"]);

            Nullable<int> HeadmanID = ViewState["SelectedHeadmanID"] as Nullable<int>;
            bool HeadmanExist = false;

            if (HeadmanID.HasValue)
            {
                foreach (Person_ViewStateItem_Pro Item in (List<Person_ViewStateItem_Pro>)lstSelectedPerson.DataSource)
                {
                    Item.Headman = (Item.dPerson.PersonID == HeadmanID);
                    HeadmanExist = Item.Headman || HeadmanExist;
                }
            }

            if (!HeadmanExist)
                ViewState["SelectedHeadmanID"] = null;

            lstSelectedPerson.DataBind();
        }

        private void FillToDropDown()
        {
            DateTime temp = DateTime.Now;
            for (int i = 0; i < 40; i++)
                ddlTo.Items.Add(temp.AddDays(i).ToShortHijriSolarDateString());
        }

        private void FillFromDropDown()
        {
            DateTime temp = DateTime.Now;
            for (int i = 0; i < 10; i++)
                ddlFrom.Items.Add(temp.AddDays(i).ToShortHijriSolarDateString());
        }

        private void FillRefererDropDown()
        {
            DataAccessLayer.linqDatabaseDataContext db = new DataAccessLayer.linqDatabaseDataContext();
            ddlReferer.DataSource = DataAccessLayer.Referer.ToList(db);
            ddlReferer.DataTextField = "DisplayName";
            ddlReferer.DataValueField = "RefererID";
            ddlReferer.DataBind();
        }

        protected void btnAddRoom_Click(object sender, EventArgs e)
        {
            int RoomID = int.Parse(((Button)sender).ToolTip);
            for (int i = 0; i < (ViewState["SearchRoom"] as List<Room_ViewStateItem>).Count; i++)
            {
                Room_ViewStateItem Item = (ViewState["SearchRoom"] as List<Room_ViewStateItem>)[i];
                if (Item.RoomID == RoomID)
                {
                    (ViewState["SelectedRoom"] as List<Room_ViewStateItem>).Add(Item);
                    (ViewState["SearchRoom"] as List<Room_ViewStateItem>).Remove(Item);
                    i--;
                }
            }
        }

        protected void btnSearchRoom_Click(object sender, EventArgs e)
        {
            string sFrom = ddlFrom.SelectedValue;
            string sTo = ddlTo.SelectedValue;
            DateTime SelectedFrom = PersianDateTimeExtension.ParseHijriSolar(sFrom).AddHours(14);
            DateTime SelectedTo = PersianDateTimeExtension.ParseHijriSolar(sTo).AddHours(12);

            DataAccessLayer.linqDatabaseDataContext db = new DataAccessLayer.linqDatabaseDataContext();

            List<DataAccessLayer.Room> Rooms = DataAccessLayer.Room.ToList(db);
            List<Room_ViewStateItem> Room_Items = new List<Room_ViewStateItem>();
            foreach (DataAccessLayer.Room ThisRoom in Rooms)
            {
                bool Exist = false;
                foreach (Room_ViewStateItem Item in (ViewState["SelectedRoom"] as List<Room_ViewStateItem>))
                    if (Item.RoomID == ThisRoom.RoomID)
                        Exist = true;
                bool Full = false;
                // determine is full
                if (!Exist && !Full)
                    Room_Items.Add(new Room_ViewStateItem() { RoomID = ThisRoom.RoomID, From = SelectedFrom, To = SelectedTo });
            }
            ViewState["SearchRoom"] = Room_Items;
        }

        protected void btnDeleteRoom_Click(object sender, EventArgs e)
        {
            int RoomID = int.Parse(((Button)sender).ToolTip);
            for (int i = 0; i < (ViewState["SelectedRoom"] as List<Room_ViewStateItem>).Count; i++)
            {
                Room_ViewStateItem Item = (ViewState["SelectedRoom"] as List<Room_ViewStateItem>)[i];
                if (Item.RoomID == RoomID)
                {
                    (ViewState["SelectedRoom"] as List<Room_ViewStateItem>).Remove(Item);
                    i--;
                }
            }
        }

        protected void btnAddPerson_Click(object sender, EventArgs e)
        {
            int PersonID = int.Parse(((Button)sender).ToolTip);
            for (int i = 0; i < (ViewState["SearchPerson"] as List<Person_ViewStateItem>).Count; i++)
            {
                Person_ViewStateItem Item = (ViewState["SearchPerson"] as List<Person_ViewStateItem>)[i];
                if (Item.PersonID == PersonID)
                {
                    (ViewState["SelectedPerson"] as List<Person_ViewStateItem>).Add(Item);
                    (ViewState["SearchPerson"] as List<Person_ViewStateItem>).Remove(Item);
                    i--;
                }
            }
        }

        protected void btnDeletePerson_Click(object sender, EventArgs e)
        {
            int PersonID = int.Parse(((Button)sender).ToolTip);
            for (int i = 0; i < (ViewState["SelectedPerson"] as List<Person_ViewStateItem>).Count; i++)
            {
                Person_ViewStateItem Item = (ViewState["SelectedPerson"] as List<Person_ViewStateItem>)[i];
                if (Item.PersonID == PersonID)
                {
                    (ViewState["SelectedPerson"] as List<Person_ViewStateItem>).Remove(Item);
                    i--;
                }
            }
        }

        protected void btnHeadman_Click(object sender, EventArgs e)
        {
            ViewState["SelectedHeadmanID"] = int.Parse(((Button)sender).ToolTip);
        }

        protected void btnSearchPerson_Click(object sender, EventArgs e)
        {
            string NationalNumber = txtNationalNumber.Text;
            string FirstName = txtFirstName.Text;
            string LastName = txtLastName.Text;
            DataAccessLayer.linqDatabaseDataContext db = new DataAccessLayer.linqDatabaseDataContext();
            List<DataAccessLayer.Person> Persons = DataAccessLayer.Person.ToList_Filter(db, FirstName, LastName, NationalNumber);
            List<Person_ViewStateItem> Person_Items = new List<Person_ViewStateItem>();
            foreach (DataAccessLayer.Person ThisPerson in Persons)
            {
                bool Exist = false;
                foreach (Person_ViewStateItem Item in (ViewState["SelectedPerson"] as List<Person_ViewStateItem>))
                    if (Item.PersonID == ThisPerson.PersonID)
                        Exist = true;
                if (!Exist)
                    Person_Items.Add(new Person_ViewStateItem() { PersonID = ThisPerson.PersonID });
            }
            ViewState["SearchPerson"] = Person_Items;
        }

        protected void btnReserve_Click(object sender, EventArgs e)
        {
            List<Room_ViewStateItem> SelectedRoom = (ViewState["SelectedRoom"] as List<Room_ViewStateItem>);
            List<Person_ViewStateItem> SelectedPerson = (ViewState["SelectedPerson"] as List<Person_ViewStateItem>);
            Nullable<int> HeadmanID = ViewState["SelectedHeadmanID"] as Nullable<int>;

            if (SelectedRoom.Count == 0)
            {
                lblNoRoomSelected.Visible = true;
                return;
            }
            if (SelectedPerson.Count == 0)
            {
                lblNoPersonSelected.Visible = true;
                return;
            }
            if (!HeadmanID.HasValue)
            {
                lblNoHeadmanSelected.Visible = true;
                return;
            }

            int EditorUserID = int.Parse(Session["UserID"].ToString());
            int RefererID;

            if (!int.TryParse(ddlReferer.SelectedValue, out RefererID))
            {
                lblInvalidInput.Visible = true;
                return;
            }

            DataAccessLayer.linqDatabaseDataContext db = new DataAccessLayer.linqDatabaseDataContext();
            DataAccessLayer.sRequest newSRequest = new DataAccessLayer.sRequest();
            db.sRequests.InsertOnSubmit(newSRequest);

            db.SubmitChanges();

            DataAccessLayer.Request newRequest = new DataAccessLayer.Request();
            newRequest.RequestID = newSRequest.ID;
            newRequest.EditorUserID = EditorUserID;
            newRequest.HeadmanPersonID = HeadmanID.Value;
            newRequest.Feedback = "";
            newRequest.Description = "";
            newRequest.RefererID = RefererID;
            newRequest.RequestStatusID = (int)BusinessLogicLayer.RequestStatus.Reserved;
            newRequest.Timestamp = DateTime.Now;
            db.Requests.InsertOnSubmit(newRequest);

            foreach (Room_ViewStateItem ThisRoom in SelectedRoom)
            {
                DataAccessLayer.RequestRoom newRequestRoom = new DataAccessLayer.RequestRoom();
                newRequestRoom.RequestID = newSRequest.ID;
                newRequestRoom.RoomID = ThisRoom.RoomID;
                newRequestRoom.EditorUserID = EditorUserID;
                newRequestRoom.OfficialStartTimestamp = ThisRoom.From;
                newRequestRoom.OfficialEndTimestamp = ThisRoom.To;
                newRequestRoom.RequestRoomStatusID = (int)BusinessLogicLayer.RequestRoomStatus.Reserved;
                newRequestRoom.Description = "";
                newRequestRoom.Timestamp = DateTime.Now;
                db.RequestRooms.InsertOnSubmit(newRequestRoom);
            }

            foreach (Person_ViewStateItem ThisPerson in SelectedPerson)
            {
                DataAccessLayer.RequestPerson newRequestPerson = new DataAccessLayer.RequestPerson();
                newRequestPerson.RequestID = newSRequest.ID;
                newRequestPerson.PersonID = ThisPerson.PersonID;
                newRequestPerson.EditorUserID = EditorUserID;
                newRequestPerson.RequestPersonStatusID = (int)BusinessLogicLayer.RequestPersonStatus.WaitForArrive;
                newRequestPerson.Timestamp = DateTime.Now;
                db.RequestPersons.InsertOnSubmit(newRequestPerson);
            }
            db.SubmitChanges();

            Response.Redirect("Request.aspx?RequestID=" + newSRequest.ID);
            lblSuccessful.Visible = true;
            btnReserve.Visible = false;
        }
    }
}